<template>
  <div class="page" v-show="isShowPage">
    <template v-if="isHideSetting">
      <!-- tab -->
      <div class="tab" :style="{ left: sidebar.opened ? '210px' : '54px' }">
        <el-tabs v-model="currentTab">
          <el-tab-pane :label="`可发房源(${enableCount})`" name="SUCCESS_LIST"></el-tab-pane>
          <el-tab-pane :label="`不可发房源(${disableCount})`" name="FAIL_LIST"></el-tab-pane>
        </el-tabs>
        <div>
          <el-button type="primary" icon="el-icon-setting" size="mini" @click="handleSetting">
            推送设置
          </el-button>
        </div>
      </div>

      <!-- list -->
      <div class="flex-1">
        <template v-if="currentTab === 'SUCCESS_LIST'">
          <PublishHouseSuccessList
            @countChange="loadPublishCount"
            @publish="handlePublishVerify"
            :total="enableCount"
          ></PublishHouseSuccessList>
        </template>
        <template v-if="currentTab === 'FAIL_LIST'">
          <PublishHouseFailList
            @portError="isShowPortErrorDialog = true"
            @countChange="loadPublishCount"
            @publish="handlePublishVerify"
            :portInfoPromise="portInfoPromise"
            :total="disableCount"
          ></PublishHouseFailList>
        </template>
      </div>

      <!-- port error dialog -->
      <el-dialog class="port-dialog" :visible.sync="isShowPortErrorDialog" center :show-close="false" width="640px">
        <div class="port">
          <el-image style="width: 240px; height: 160px;" :src="require('@/assets/images/list_warn@1x.png')"></el-image>
          <div class="mt30">您还未绑定相应的端口账号，前往绑定后即可极速发房～</div>
          <el-button class="port-btn" type="primary" round @click="handleJumpBindPort">前往绑定</el-button>
          <el-button class="port-btn-cancel" type="text" @click="handleHidePortDialog">取消</el-button>
        </div>
      </el-dialog>

      <!-- publish comfirm dialog -->
      <PublishHouseDialog
        v-if="isShowPublishDialog"
        :isShow.sync="isShowPublishDialog"
        @publish="handlePublish"
        title="房源推送确认"
        :portInfo="portInfo"
      ></PublishHouseDialog>
    </template>
    <template v-else>
      <PublishHouseSetting :currentSetting="currentSetting" @submit="onSubmit"></PublishHouseSetting>
    </template>
  </div>
</template>
<script>
import { HOUSE_PUSH } from '@/config/menuId';
import { checkPortAccountHandler, getPushAblePortList, menuHandler, resetPortStatus } from '@/handler/menuHandler';
import PublishHouseSetting from './com/PublishHouseSetting';
import PublishHouseFailList from './com/PublishHouseFailList';
import PublishHouseSuccessList from './com/PublishHouseSuccessList';
import PublishHouseDialog from './com/PublishHouseDialog.vue';
import { mapGetters } from 'vuex';

export default {
  name: 'PublishHouseList',
  components: {
    PublishHouseSetting,
    PublishHouseFailList,
    PublishHouseSuccessList,
    PublishHouseDialog
  },
  props: {},
  data() {
    this.currentPublish = [];
    this.currentPublishHandler = '';
    return {
      portInfo: [],
      isShowPortErrorDialog: false,
      isShowPublishDialog: false,
      portInfoPromise: null,
      isShowPage: false,
      currentSetting: null,
      isHideSetting: false,
      currentTab: 'SUCCESS_LIST',
      enableCount: 0,
      disableCount: 0
    };
  },
  created() {},
  async mounted() {
    resetPortStatus();
    await this.loadPublishCount();
    this.portInfoPromise = this.getUserPortInfo();
    this.getSetting();
  },
  watch: {},
  computed: {
    ...mapGetters(['sessionUser']),
    ...mapGetters(['sidebar'])
  },
  methods: {
    // 加载推送配置
    async getSetting() {
      try {
        let res = await this.$api.getSetting();
        if (res && res.isSuccess && res.content) {
          this.isHideSetting = true;
          this.currentSetting = res.content;
        }
        this.isShowPage = true;
      } catch (error) {
        this.$message({
          message: '网络错误，请稍后重试...',
          type: 'warning'
        });
        console.log('error', error);
      }
    },
    // 保存推送配置
    async onSubmit(e) {
      try {
        let params = {
          id: this.currentSetting ? this.currentSetting.id : ''
        };
        Object.keys(e).forEach((item) => {
          item === 'saleProportion' || item === 'rentProportion'
            ? (params[item] = Number(e[item]))
            : (params[item] = e[item]);
        });
        let res = await this.$api.saveSetting(params);
        if (res && res.isSuccess && res.content) {
          this.currentSetting = res.content;
          this.isHideSetting = true;
        }
      } catch (error) {
        console.log('error', error);
      }
    },
    // 编辑推送配置
    handleSetting() {
      this.isHideSetting = false;
    },
    // 加载房源总数统计
    async loadPublishCount() {
      try {
        const portType = await getPushAblePortList();
        const res = await this.$api.pushListCount({ delegationType: 'SALES', portType });
        this.enableCount = res.content.enableCount;
        this.disableCount = res.content.disableCount;
      } catch (error) {
        console.log('error', error);
      }
    },
    // 获取用户端口信息
    getUserPortInfo() {
      return new Promise((resolve, reject) => {
        checkPortAccountHandler()
          .then((accounts) => {
            this.portInfo = accounts;
            resolve(true);
          })
          .catch(() => {
            resolve(false);
          });
      });
    },
    // 推送端口校验
    checkPort() {
      return new Promise((resolve, reject) => {
        this.portInfoPromise.then((hasPort) => {
          if (!hasPort) {
            this.isShowPortErrorDialog = true;
            return reject();
          }
          resolve();
        });
      });
    },
    // 推送会员权限校验
    checkUser() {
      return new Promise((resolve, reject) => {
        menuHandler
          .call(this, HOUSE_PUSH, this.currentPublish.length)
          .then(() => {
            resolve();
          })
          .catch(() => {
            reject();
          });
      });
    },
    // 推送前校验
    handlePublishVerify(e) {
      this.currentPublish = e.data;
      this.currentPublishHandler = e.handler;
      this.checkPort()
        .then(() => {
          return this.checkUser();
        })
        .then(() => {
          this.isShowPublishDialog = true;
        })
        .catch((err) => {
          console.log('推送校验失败', err);
        });
    },
    // 推送
    async handlePublish(e) {
      try {
        this.isShowPublishDialog = false;
        const { currentPublish, currentPublishHandler } = this;
        const res = await this.$api.pushHouNew({
          delList: currentPublish,
          pushHouVoList: e.map((item) => {
            return {
              portType: item.portType,
              houType: item.houseType,
              pushType: item.publishType
            };
          }),
          delegationType: 'SALES'
        });
        if (res && res.isSuccess) {
          this.$api.getMemberPower({
            menuId: HOUSE_PUSH,
            agentId: this.sessionUser.id,
            num: currentPublish.length
          });
          currentPublishHandler && currentPublishHandler();
        } else {
          this.$message.error('推送失败，请稍后再试~');
        }
      } catch (error) {
        console.log('error', error);
      }
    },
    // 隐藏端口错误弹窗
    handleHidePortDialog() {
      this.isShowPortErrorDialog = false;
    },
    // 跳转绑定端口
    handleJumpBindPort() {
      this.$router.push({ name: 'portManagement' });
    }
  }
};
</script>
<style lang="scss" scoped>
.page {
  display: flex;
  flex-direction: column;
  position: relative;
  padding-top: 40px;
  min-height: calc(100vh - 84px);
  background-color: #f6f6f6;
  overflow: auto;
}

.tab {
  position: fixed;
  top: 84px;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  background-color: #fff;
  z-index: 2;
  transition: all 0.3s;

  & /deep/ .el-tabs__nav-wrap::after {
    background-color: #fff;
  }

  & /deep/ .el-tabs__header {
    margin: 0;
  }
}

.port-dialog /deep/ .el-dialog {
  border-radius: 20px;
}

.port {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .port-btn {
    margin-top: 40px;
    width: 240px;
    height: 48px;
    border-radius: 999px;
    padding: 0;
    font-weight: 700;
  }

  .port-btn-cancel {
    margin: 20px 0 0;
    font-weight: 700;
  }
}
</style>
